package org.springblade.modules.door.device;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.alioss.AliyunOSSConfig;
import org.springblade.modules.alioss.model.FileOss;
import org.springblade.modules.door.dto.DoorDeviceMsgDto;
import org.springblade.modules.door.entity.DoorDevice;
import org.springblade.modules.door.entity.DoorLogFile;
import org.springblade.modules.door.mapper.DoorLogFileMapper;
import org.springblade.modules.door.service.IDoorDeviceService;
import org.springblade.modules.door.vo.DoorDeviceVo;
import org.springblade.modules.resource.service.FileUploadService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@RestController
@AllArgsConstructor
@RequestMapping("/door/device")
@Slf4j
public class DeviceController {
	private final IDoorDeviceService doorDeviceService;
	private final FileUploadService fileUploadService;
	private final AliyunOSSConfig aliyunOSSConfig;
	private final DoorLogFileMapper doorLogFileMapper;

	/**
	 * 详情
	 */
	@GetMapping("/register")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "开门柜注册初始化", notes = "开门柜注册初始化")
	public R<DoorDeviceVo> register(String deviceCode, String readerSn) {
		DoorDeviceVo doorDeviceVo = null;
		try {
			doorDeviceVo = doorDeviceService.register(deviceCode,readerSn);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("设备注册失败",e);
		}
		return R.data(doorDeviceVo);
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperation(value = "分页", notes = "传入deviceDoor")
	public R<IPage<DoorDevice>> list(DoorDevice doorDevice, Query query) {
		LambdaQueryWrapper<DoorDevice> deviceWrapper = Wrappers.lambdaQuery();
		deviceWrapper
			.like(StringUtils.isNotBlank(doorDevice.getDeviceCode()),DoorDevice::getDeviceCode, doorDevice.getDeviceCode())
			.like(StringUtils.isNotBlank(doorDevice.getClientId()),DoorDevice::getClientId,doorDevice.getClientId())
			.like(StringUtils.isNotBlank(doorDevice.getReaderSn()),DoorDevice::getReaderSn,doorDevice.getReaderSn())
			.orderByDesc(DoorDevice::getCreateTime);
		IPage<DoorDevice> pages = doorDeviceService.page(Condition.getPage(query), deviceWrapper);
		return R.data(pages);
	}

	/**
	 * 分页
	 */
	@GetMapping("/detail")
	@ApiOperation(value = "分页", notes = "传入deviceDoor")
	public R<DoorDevice> detail(Long id) {
		return R.data(doorDeviceService.getById(id));
	}


	/**
	 * 分页
	 */
	@PostMapping("/updateDevice")
	@ApiOperation(value = "分页", notes = "传入deviceDoor")
	public R<Boolean> updateDevice(@RequestBody DoorDevice doorDevice) {
		return R.data(doorDeviceService.updateById(doorDevice));
	}


	/**
	 * 分页
	 */
	@PostMapping("/sendDoorMsg")
	@ApiOperation(value = "分页", notes = "传入deviceDoor")
	public R<Boolean> sendDoorMsg(@RequestBody DoorDeviceMsgDto doorDeviceMsgDto) {
		boolean a = doorDeviceService.sendDoorMsg(doorDeviceMsgDto);
		return R.data(a);
	}

	@PostMapping("/upload")
	public R<FileOss> upload(@RequestParam MultipartFile file,String deviceCode) {
		if (file == null || file.isEmpty()) {
			throw new ServiceException("文件不能为空");
		}
		if (StringUtils.isBlank(deviceCode)) {
			throw new ServiceException("设备信息不能为空");
		}
		String originalFileName = file.getOriginalFilename();
		if (StringUtils.isBlank(originalFileName)) throw new RuntimeException("非法文件名");
		String fileName = fileUploadService.getFileName(aliyunOSSConfig.getDoorPrefix(), originalFileName);
		FileOss fileOss = fileUploadService.upload(file, fileName);
		DoorLogFile doorLogFile = new DoorLogFile();
		Pair<String, String> logFileMatt = getLogFileName(originalFileName,deviceCode);
		doorLogFile.setDeviceCode(logFileMatt.getLeft());
		doorLogFile.setLogDate(logFileMatt.getRight());
		doorLogFile.setName(originalFileName);
		doorLogFile.setPath(fileOss.getPath());
		doorLogFile.setFullPath(fileOss.getFullPath());
		doorLogFile.setUploadTime(new Date());
		doorLogFileMapper.insert(doorLogFile);
		return R.data(fileOss);
	}

	private Pair<String, String> getLogFileName(String originalFileName,String deviceCode){
		//20250723_1753317300021.txt
		String fileNamePre = originalFileName.substring(0, originalFileName.indexOf("."));
		String date = "";
		if(originalFileName.contains("-")){
			date = StringUtil.sub(originalFileName, 0, 10);
		}else {
			date = StringUtil.sub(originalFileName, 0, 8);
		}
		return Pair.of(deviceCode,date);
	}


	@GetMapping("/downloadLogUrl")
	public void downloadLogUrl(HttpServletRequest request, HttpServletResponse response, @RequestParam String deviceCode,
									 @RequestParam String date) {
		doorDeviceService.downloadLogUrl(request,response,deviceCode,date);
	}

}
